import React, { useState, useEffect } from 'react';
import dayjs from 'dayjs';
import { 
  Table, 
  Button, 
  Form, 
  Input, 
  Modal, 
  message, 
  Pagination, 
  Space, 
  Select, 
  Card,
  Tag,
  Row,
  Col,
  DatePicker
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  KeyOutlined,
  UserOutlined,
  SearchOutlined,
  ClearOutlined
} from '@ant-design/icons';
import { 
  getAllUsers, 
  addUser, 
  updateUser, 
  updatePassword,
  type User, 
  type AddUserParams, 
  type UpdateUserParams,
  type UpdatePasswordParams
} from '../api/userManagement';
import { 
  getPermissionOptions, 
  parseUserPermissions, 
  getPermissionModuleName 
} from '../utils/routePermission';
import './UserManagement.css';

const { Option } = Select;

const UserManagement: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchKeyword, setSearchKeyword] = useState('');
  
  // 筛选状态
  const [createTimeRange, setCreateTimeRange] = useState<[any, any] | null>(null);
  const [loginTimeRange, setLoginTimeRange] = useState<[any, any] | null>(null);
  const [levelFilter, setLevelFilter] = useState<number | undefined>(undefined);
  const [statusFilter, setStatusFilter] = useState<"1" | "0" | undefined>(undefined);

  // 弹窗状态
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [currentUser, setCurrentUser] = useState<User | null>(null);

  // 表单实例
  const [addForm] = Form.useForm();
  const [editForm] = Form.useForm();
  const [passwordForm] = Form.useForm();

  // 权限选项 - 使用新的权限配置
  const permissionOptions = getPermissionOptions();

  // 级别选项
  const levelOptions = [
    { value: 1, label: '1级 - 管理员' },
    { value: 2, label: '2级 - 操作员' }
  ];

  // 状态选项
  const statusOptions = [
    { value: "1", label: '已激活' },
    { value: "0", label: '未激活' }
  ];

  // 日期选择限制函数 - 禁用未来日期
  const disabledDate = (current: any) => {
    // 不能选择未来日期
    return current && current.isAfter(dayjs().endOf('day'));
  };

  // 获取筛选参数
  const getFilterParams = () => {
    const params: any = {
      page: current,
      ps: pageSize,
      key: searchKeyword
    };

    // 创建时间范围
    if (createTimeRange && createTimeRange[0] && createTimeRange[1]) {
      params.cbt = createTimeRange[0].format('YYYY-MM-DD') + ' 00:00:00';
      params.cet = createTimeRange[1].format('YYYY-MM-DD') + ' 23:59:59';
    }

    // 登录时间范围
    if (loginTimeRange && loginTimeRange[0] && loginTimeRange[1]) {
      params.lbt = loginTimeRange[0].format('YYYY-MM-DD') + ' 00:00:00';
      params.let = loginTimeRange[1].format('YYYY-MM-DD') + ' 23:59:59';
    }

    // 等级筛选
    if (levelFilter !== undefined) {
      params.level = levelFilter;
    }

    // 状态筛选 - 传递字符串类型
    if (statusFilter !== undefined) {
      params.is_active = statusFilter;
    }

    return params;
  };

  // 清空筛选条件
  const clearFilters = () => {
    setSearchKeyword('');
    setCreateTimeRange(null);
    setLoginTimeRange(null);
    setLevelFilter(undefined);
    setStatusFilter(undefined);
  };

  // 获取用户列表
  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await getAllUsers(getFilterParams());
      
      if (response.code === 0 && response.data) {
        setUsers(response.data.users || []);
        setTotal(response.data.total || 0);
      } else {
        // 如果接口返回错误或没有数据，使用模拟数据
        const mockUsers: User[] = [
          {
            uid: 1,
            user: 'admin',
            name: '系统管理员',
            mobile: '13800138000',
            user_perm: '数据归档,数据管理,运行管理',
            level: 1,
            createTime: '2023-01-01 10:00:00',
            lastLoginTime: '2024-01-15 14:30:00',
            status: 'active'
          },
          {
            uid: 2,
            user: 'operator01',
            name: '操作员001',
            mobile: '13800138001',
            user_perm: '数据管理,数据检索',
            level: 2,
            createTime: '2023-02-15 09:00:00',
            lastLoginTime: '2024-01-14 16:20:00',
            status: 'active'
          },
          {
            uid: 3,
            user: 'user001',
            name: '普通用户001',
            mobile: '13800138002',
            user_perm: '数据检索',
            level: 3,
            createTime: '2023-03-20 11:30:00',
            lastLoginTime: '2024-01-10 10:15:00',
            status: 'active'
          }
        ];
        setUsers(mockUsers);
        setTotal(mockUsers.length);
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时获取数据
  useEffect(() => {
    fetchUsers();
  }, [current, pageSize, searchKeyword, createTimeRange, loginTimeRange, levelFilter, statusFilter]);

  // 监听添加用户表单level变化，level为1时自动全选权限
  useEffect(() => {
    const currentLevel = addForm.getFieldValue('level');
    if (currentLevel === 1) {
      addForm.setFieldsValue({ user_perm: permissionOptions.map(opt => opt.value) });
    } else if (currentLevel === 2) {
      // 操作员级别清空权限，让用户手动选择
      addForm.setFieldsValue({ user_perm: [] });
    }
  }, [addForm.getFieldValue('level'), permissionOptions]);

  // 监听编辑用户表单level变化，level为1时自动全选权限
  useEffect(() => {
    const currentLevel = editForm.getFieldValue('level');
    if (currentLevel === 1) {
      editForm.setFieldsValue({ user_perm: permissionOptions.map(opt => opt.value) });
    }
  }, [editForm.getFieldValue('level'), permissionOptions]);

  // 添加用户
  const handleAddUser = async (values: any) => {
    try {
      // 管理员(level=1)自动设置所有权限，操作员需要验证权限选择
      let userPerm: string[] = values.user_perm || [];
      if (Number(values.level) === 1) {
        userPerm = permissionOptions.map(opt => opt.value);
      } else {
        // 操作员级别必须选择权限
        if (!userPerm || userPerm.length === 0) {
          message.error('操作员用户必须选择至少一个权限');
          return;
        }
      }
      
      // 确保user_perm是字符串格式
      const formData: AddUserParams = {
        ...values,
        user_perm: Array.isArray(userPerm) ? userPerm.join(',') : userPerm
      };
      const response = await addUser(formData);
      console.log('添加用户响应:', response); // 调试日志
      if (response.code === 0) {
        message.success(response.message || '添加用户成功');
        setAddModalVisible(false);
        addForm.resetFields();
        fetchUsers();
      } else {
        message.error(response.message || '添加用户失败');
      }
    } catch (error: any) {
      console.error('添加用户异常:', error);
      message.error(error?.message || '添加用户失败');
    }
  };

  // 编辑用户
  const handleEditUser = async (values: UpdateUserParams) => {
    try {
      const response = await updateUser(values);
      if (response.code === 0) {
        message.success('修改用户信息成功');
        setEditModalVisible(false);
        editForm.resetFields();
        fetchUsers();
      } else {
        message.error(response.message || '修改用户信息失败');
      }
    } catch (error) {
      message.error('修改用户信息失败');
    }
  };

  // 修改密码
  const handleUpdatePassword = async (values: UpdatePasswordParams) => {
    try {
      const response = await updatePassword(values);
      if (response.code === 0) {
        message.success('修改密码成功');
        setPasswordModalVisible(false);
        passwordForm.resetFields();
      } else {
        message.error(response.message || '修改密码失败');
      }
    } catch (error) {
      message.error('修改密码失败');
    }
  };



  // 打开编辑弹窗
  const openEditModal = (user: User) => {
    setCurrentUser(user);
    
    // 解析权限数据，支持JSON和逗号分隔格式
    let permissionValues: string[] = [];
    try {
      const permissions = parseUserPermissions(user.user_perm, user.level as any);
      permissionValues = permissions.modules;
    } catch (error) {
      // 兼容旧的逗号分隔格式
      permissionValues = user.user_perm.split(',').map(p => p.trim()).filter(Boolean);
    }
    
    editForm.setFieldsValue({
      ...user,
      user_perm: permissionValues
    });
    setEditModalVisible(true);
  };

  // 表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 60,
      align: 'center' as const,
      render: (_: any, __: any, index: number) => index + 1 + (current - 1) * pageSize,
    },
    {
      title: '用户名',
      dataIndex: 'user',
      key: 'user',
      width: 120,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
    },
    {
      title: '手机号',
      dataIndex: 'mobile',
      key: 'mobile',
      width: 120,
    },

    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      width: 120,
      render: (level: number) => {
        const levelMap = {
          1: { text: '1级 - 管理员', color: 'red' },
          2: { text: '2级 - 操作员', color: 'orange' }
        };
        const levelInfo = levelMap[level as keyof typeof levelMap] || { text: `${level}级`, color: 'default' };
        return <Tag color={levelInfo.color}>{levelInfo.text}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '已激活' : '未激活'}
        </Tag>
      ),
    },
    {
      title: '权限',
      dataIndex: 'user_perm',
      key: 'user_perm',
      width: 220,
      render: (userPerm: string, record: User) => {
        // 管理员用户直接显示"全部"
        if (Number(record.level) === 1) {
          return <Tag color="red" style={{ fontWeight: 'bold' }}>全部</Tag>;
        }
        
        try {
          // 解析权限数据
          const permissions = parseUserPermissions(userPerm, record.level as any);
          const permissionNames = permissions.modules.map(module => 
            getPermissionModuleName(module)
          );
          
          if (permissionNames.length === 0) {
            return <Tag color="default">无权限</Tag>;
          }
          
          return (
            <div style={{ 
              maxWidth: '200px', 
              wordBreak: 'break-word',
              lineHeight: '1.5',
              paddingRight: '8px'
            }}>
              {permissionNames.map((name, index) => (
                <Tag key={index} color="blue" style={{ 
                  marginBottom: 4, 
                  marginRight: 4,
                  display: 'inline-block'
                }}>
                  {name}
                </Tag>
              ))}
            </div>
          );
        } catch (error) {
          // 兼容旧的逗号分隔格式
          const permNames = userPerm.split(',').filter(Boolean);
          return (
            <div style={{ 
              maxWidth: '200px', 
              wordBreak: 'break-word',
              lineHeight: '1.5',
              paddingRight: '8px'
            }}>
              {permNames.map((name, index) => (
                <Tag key={index} color="blue" style={{ 
                  marginBottom: 4, 
                  marginRight: 4,
                  display: 'inline-block'
                }}>
                  {name.trim()}
                </Tag>
              ))}
            </div>
          );
        }
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right' as const,
      render: (_: any, record: User) => (
        <Space>
          <Button 
            size="small" 
            icon={<EditOutlined />} 
            onClick={() => openEditModal(record)}
          >
            编辑
          </Button>
          <Button 
            size="small" 
            icon={<KeyOutlined />} 
            onClick={() => setPasswordModalVisible(true)}
          >
            改密
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="user-management-container">
      {/* 主内容区域 */}
      <div className="user-management-page">
        <Card>
          {/* 筛选操作栏 */}
          <Row gutter={16} style={{ marginBottom: 16 }}>
            <Col span={4}>
              <Input
                placeholder="请输入用户名或姓名搜索"
                allowClear
                value={searchKeyword}
                onChange={e => setSearchKeyword(e.target.value)}
                style={{ width: '100%' }}
              />
            </Col>
            <Col span={4}>
              <DatePicker.RangePicker
                value={createTimeRange}
                onChange={(dates) => {
                  // 检查日期范围是否超过7天
                  if (dates && dates[0] && dates[1]) {
                    const diffDays = dates[1].diff(dates[0], 'day');
                    if (diffDays > 7) {
                      // 如果超过7天，显示提示并重置
                      message.warning('日期范围不能超过7天');
                      setCreateTimeRange(null);
                      return;
                    }
                  }
                  setCreateTimeRange(dates);
                }}
                disabledDate={disabledDate}
                format="YYYY-MM-DD"
                placeholder={['创建开始', '创建结束']}
                style={{ width: '100%' }}
              />
            </Col>
            <Col span={4}>
              <DatePicker.RangePicker
                value={loginTimeRange}
                onChange={(dates) => {
                  // 检查日期范围是否超过7天
                  if (dates && dates[0] && dates[1]) {
                    const diffDays = dates[1].diff(dates[0], 'day');
                    if (diffDays > 7) {
                      // 如果超过7天，显示提示并重置
                      message.warning('日期范围不能超过7天');
                      setLoginTimeRange(null);
                      return;
                    }
                  }
                  setLoginTimeRange(dates);
                }}
                disabledDate={disabledDate}
                format="YYYY-MM-DD"
                placeholder={['登录开始', '登录结束']}
                style={{ width: '100%' }}
              />
            </Col>
            <Col span={3}>
              <Select
                value={levelFilter}
                onChange={setLevelFilter}
                placeholder="选择等级"
                allowClear
                style={{ width: '100%' }}
              >
                {levelOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col span={3}>
              <Select
                value={statusFilter}
                onChange={setStatusFilter}
                placeholder="选择状态"
                allowClear
                style={{ width: '100%' }}
              >
                {statusOptions.map(option => (
                  <Option key={option.value} value={option.value}>
                    {option.label}
                  </Option>
                ))}
              </Select>
            </Col>
            <Col span={5} style={{ textAlign: 'right' }}>
              <Space>
                <Button 
                  icon={<ClearOutlined />}
                  onClick={clearFilters}
                  title="清空筛选"
                >
                  清空
                </Button>
                <Button 
                  icon={<SearchOutlined />} 
                  onClick={fetchUsers}
                  title="搜索用户"
                  style={{ backgroundColor: '#1890ff', borderColor: '#1890ff', color: 'white' }}
                >
                  搜索
                </Button>
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />}
                  onClick={() => setAddModalVisible(true)}
                >
                  添加用户
                </Button>
              </Space>
            </Col>
          </Row>

          {/* 用户列表表格 */}
          <Table
            columns={columns}
            dataSource={users}
            loading={loading}
            rowKey="uid"
            pagination={false}
            scroll={{ x: 'max-content' }}
            bordered
            size="small"
            rowClassName={(_, index) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
          />

          {/* 分页 */}
          <div style={{ marginTop: 16, textAlign: 'right' }}>
            <Pagination
              current={current}
              pageSize={pageSize}
              total={total}
              showSizeChanger
              pageSizeOptions={['10', '20', '50']}
              onChange={(page, size) => {
                setCurrent(page);
                setPageSize(size!);
              }}
              showTotal={total => `共 ${total} 条`}
            />
          </div>
        </Card>
      </div>

      {/* 添加用户弹窗 */}
      <Modal
        title={<><UserOutlined /> 添加用户</>}
        open={addModalVisible}
        onCancel={() => {
          setAddModalVisible(false);
          addForm.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={addForm}
          layout="vertical"
          onFinish={handleAddUser}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="user"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { pattern: /^[a-zA-Z0-9_]{3,20}$/, message: '用户名只能包含字母、数字、下划线，长度3-20位' }
                ]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label="姓名"
                rules={[{ required: true, message: '请输入姓名' }]}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码长度至少6位' }
                ]}
              >
                <Input.Password placeholder="请输入密码" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="passwordv"
                label="确认密码"
                dependencies={['password']}
                rules={[
                  { required: true, message: '请确认密码' },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue('password') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不一致'));
                    },
                  }),
                ]}
              >
                <Input.Password placeholder="请确认密码" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="mobile"
                label="手机号"
                rules={[
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>

            <Col span={12}>
              <Form.Item
                name="level"
                label="级别"
                rules={[{ required: true, message: '请选择级别' }]}
              >
                <Select placeholder="请选择级别">
                  {levelOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={24}>
              <Form.Item shouldUpdate={(prevValues, currentValues) => prevValues.level !== currentValues.level}>
                {({ getFieldValue }) => {
                  const selectedLevel = getFieldValue('level');
                  const isAdmin = Number(selectedLevel) === 1;
                  
                  return (
                    <Form.Item
                      name="user_perm"
                      label="用户权限"
                      rules={isAdmin ? [] : [{ required: true, message: '请选择用户权限' }]}
                    >
                      {isAdmin ? (
                        <div>
                          <Select
                            mode="multiple"
                            placeholder="管理员拥有所有权限"
                            style={{ width: '100%' }}
                            disabled
                            value={permissionOptions.map(opt => opt.value)}
                          >
                            {permissionOptions.map(option => (
                              <Option key={option.value} value={option.value}>
                                {option.label}
                              </Option>
                            ))}
                          </Select>
                          <div style={{ marginTop: 4, color: '#999', fontSize: '12px' }}>
                            管理员用户拥有所有权限，无需单独配置
                          </div>
                        </div>
                      ) : (
                        <Select
                          mode="multiple"
                          placeholder="请选择用户权限"
                          style={{ width: '100%' }}
                        >
                          {permissionOptions.map(option => (
                            <Option key={option.value} value={option.value}>
                              {option.label}
                            </Option>
                          ))}
                        </Select>
                      )}
                    </Form.Item>
                  );
                }}
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="is_active"
                label="激活状态"
                rules={[{ required: true, message: '请选择激活状态' }]}
              >
                <Select>
                  <Option value={"1"}>已激活</Option>
                  <Option value={"0"}>未激活</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item style={{ marginTop: 24, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setAddModalVisible(false);
                addForm.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑用户弹窗 */}
      <Modal
        title={<><EditOutlined /> 编辑用户</>}
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          editForm.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={editForm}
          layout="vertical"
          onFinish={(values) => {
            if (currentUser) {
              // 管理员(level=1)的权限设置为所有权限
              let userPerm = values.user_perm;
              if (Number(currentUser.level) === 1) {
                userPerm = permissionOptions.map(opt => opt.value);
              }
              
              handleEditUser({
                uid: currentUser.uid!,
                ...values,
                user_perm: Array.isArray(userPerm) ? userPerm.join(',') : userPerm
              });
            }
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="姓名"
                rules={[{ required: true, message: '请输入姓名' }]}
              >
                <Input placeholder="请输入姓名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="mobile"
                label="手机号"
                rules={[
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="level"
                label="级别"
                rules={[{ required: true, message: '请选择级别' }]}
              >
                <Select placeholder="请选择级别">
                  {levelOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="user_perm"
                label="用户权限"
                rules={[{ required: true, message: '请选择用户权限' }]}
              >
                {/* 管理员(level=1)编辑时禁用权限选择，并显示提示 */}
                {currentUser && Number(currentUser.level) === 1 ? (
                  <div>
                    <Select
                      mode="multiple"
                      placeholder="管理员拥有所有权限"
                      style={{ width: '100%' }}
                      disabled
                      value={permissionOptions.map(opt => opt.value)}
                    >
                      {permissionOptions.map(option => (
                        <Option key={option.value} value={option.value}>
                          {option.label}
                        </Option>
                      ))}
                    </Select>
                    <div style={{ marginTop: 4, color: '#999', fontSize: '12px' }}>
                      管理员用户拥有所有权限，无需单独配置
                    </div>
                  </div>
                ) : (
                  <Select
                    mode="multiple"
                    placeholder="请选择用户权限"
                    style={{ width: '100%' }}
                  >
                    {permissionOptions.map(option => (
                      <Option key={option.value} value={option.value}>
                        {option.label}
                      </Option>
                    ))}
                  </Select>
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="is_active"
                label="激活状态"
                rules={[{ required: true, message: '请选择激活状态' }]}
              >
                <Select>
                  <Option value={"1"}>已激活</Option>
                  <Option value={"0"}>未激活</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item style={{ marginTop: 24, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setEditModalVisible(false);
                editForm.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改密码弹窗 */}
      <Modal
        title={<><KeyOutlined /> 修改密码</>}
        open={passwordModalVisible}
        onCancel={() => {
          setPasswordModalVisible(false);
          passwordForm.resetFields();
        }}
        footer={null}
        width={400}
      >
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handleUpdatePassword}
        >
          <Form.Item
            name="password"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度至少6位' }
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>

          <Form.Item
            name="passwordv"
            label="确认密码"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请确认密码" />
          </Form.Item>

          <Form.Item style={{ marginTop: 24, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => {
                setPasswordModalVisible(false);
                passwordForm.resetFields();
              }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement; 